package com.fdb.efp.nls.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.DecimalFormat;

public class SocketClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(SocketClientUtil.class);

    public static final String CHARSET_GBK = "GBK";
    public static final String GJJ_HEAD = "1a9x";
    public static final String GJJ_KEY = "1234567887654321";//key值需要修改


    /**
     * @param
     * @return
     * @throws
     * @throws IOException
     */
    //公积金接口开发
    public byte[] sendMessageGjj(String message,String ip,String port) throws  Exception {
        BufferedOutputStream out=null;
        BufferedInputStream in =null;
        Socket client = null;
        try {

            client = new Socket(ip,Integer.parseInt(port));

            client.setSoTimeout(20000);//设定超时时间

            out = new BufferedOutputStream(client.getOutputStream());
            in = new  BufferedInputStream(client.getInputStream());

            byte[] docOut = null;
            docOut = message.getBytes(CHARSET_GBK);
            logger.info("请求报文："+new String(docOut, CHARSET_GBK));
            //请求报文加密
            String heanCom = "1a9x";

            //加密
//			byte[] docOutEnc = DesUtil.encDataByTripleDes(
//					docOut,DesUtil.MODE_NOPADDING,(byte)0,"12345678,87654321,12345678".split(","));
            byte[] reqEnc = AESUtil.encrypt(docOut, GJJ_KEY);

            String newreqStr = Base64Utils.encode(reqEnc);
            String reqStr = GJJ_HEAD + intToString(newreqStr.length(), 6)+newreqStr;
            byte[] reqEncRtn = reqStr.getBytes(CHARSET_GBK);
//			reqEncRtn= SocketHelper.wrapMessagePackage(reqEncRtn,MSG_HEAD_LEN);
            logger.info("请求报文1："+new String(reqEncRtn, CHARSET_GBK));
            out.write(reqEncRtn);
            out.flush();

            //处理返回值
            byte[] b = new byte[10];
            in.read(b,0,10);
            String len=new String(b, CHARSET_GBK);
            logger.info("====>处理返回值:"+len+" =====>长度："+len.substring(4,10));

            int length=Integer.parseInt(len.substring(4,10));
//			byte[] msgByte=new byte[length+10];
//			in.read(msgByte, 0, 10+length);

            byte[] msgByte=new byte[length];
            StringBuffer rspbf = new StringBuffer();
            String rsp="";
            int i=0;
            int size=0;
            while(size<length){
                i++;
                size+=in.read(msgByte,size,length-size);
//				rspbf.append(new String(msgByte, CommConstant.CHARSET_GBK));
                logger.info("=========>读流循环次数："+i);
            }
            rsp = new String(msgByte, CHARSET_GBK);
            rspbf.setLength(0);


            //解密文件
            //byte[] msgByteDecData = DesUtil.decDataByTripleDes(
            //	msgByte,DesUtil.MODE_NOPADDING,(byte)0,"12345678,87654321,12345678".split(","));
            //解密返回报文
            //System.out.println("返回报文  As:"+ rsp);
            byte[] msgByteDecData = Base64Utils.decode(rsp);
            msgByteDecData = AESUtil.decrypt(msgByteDecData, GJJ_KEY);
//            String requestString = new String(msgByteDecData, CHARSET_GBK);
//            logger.info("=========>解密返回报文："+ requestString);

            return msgByteDecData;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } finally {
            try {
                if(out!=null) out.close();
                if(in!=null) in.close();
                if(client!=null) client.close();
            } catch (IOException e) {
            }
        }

    }

    public static String intToString(long n, int l) {
        DecimalFormat decimalFormat = new DecimalFormat(initString(
                '0', l));
        return decimalFormat.format(n);
    }

    public static String initString(char ch, int length) {
        if (length < 0)
            return "";
        char chars[] = new char[length];
        for (int i = 0; i < length; i++)
            chars[i] = ch;
        return new String(chars);
    }



}
